<?php

require_once APPPATH.'libraries/blocks/block_instance.php';

class Block_model extends Model {
	public $parents = array(); // assoc. array of master block records (block_id => data)
	
	function Block_model()
	{
		parent::Model();
	}
	
	// if $is_content is true, $content must be passed, and the blocks loaded will respect block_exclusion records
	function load_blocks_for($location, $size, $is_content = false, $content = null)
	{
		global $BBX;
		
		$blocks  = array();
		$params  = array(
			$size,
			$location,
			$BBX['bricabox']->id
		);
		
		// is this for an entry?
		if ($is_content)
		{
			// filter out blocks who can't be rendered for this content type
			$params[] = $content->content_type_id;
			$query 	  = $this->db->query('select binst.* from block_instances binst
				where binst.size_mode = ? and binst.location = ? and binst.bricabox_id = ?
					and binst.id not in
						(select bex.block_instance_id from block_exclusions bex where bex.content_type_id = ?)
				order by binst.position asc', $params);
		}
		else
		{
			// just grab 'em all
			$query = $this->db->query('select * from block_instances
				where size_mode = ? and location = ? and bricabox_id = ?
				order by position asc', $params);
		}
		
		if ($query->num_rows())
		{
			foreach ($query->result() as $row)
			{
				// if we've already loaded a copy of the parent block, use that
				if (isset($this->parents[$row->block_id]))
				{
					$parent = $this->parents[$row->block_id];
				}
				else
				{
					$parent	= $this->db->query('select * from blocks where id = ?', $row->block_id);
					$this->parents[$row->block_id] = $parent;
				}
				
				// push the instance data
				$tpl	  = $this->build_template_path_for($parent->first_row()->name);
				$blocks[] = array('data' => $row, 'template_path' => $tpl, 'parent' => $parent->first_row());
			}
		}
		
		return $blocks;
	}
	
	function load_blocks_for_location($location, $is_content = false, $content = null)
	{
		$blocks = array(
			'large' => $this->load_blocks_for($location, 'large', $is_content, $content),
			'small' => $this->load_blocks_for($location, 'small', $is_content, $content)
		);
		return $blocks;
	}
	
	// loads all blocks that can exist in a filtered list view
	function load_blocks_for_list_view()
	{
		//return array_merge($this->load_blocks_for('homepage', 'large'), $this->load_blocks_for('homepage', 'small')); // temporary
		return $this->load_blocks_for('homepage', 'small');
	}
	
	function build_template_path_for($name)
	{
		return BlockInstance::get_template_path($name);
	}
	
	function get_parent($instance_id)
	{
		return $this->db->query('select blocks.* from blocks
			where id =
				(select block_instances.block_id from block_instances where id = ?)
			limit 1',
				array($instance_id)
		)->first_row();
	}
	
	function get_instance($instance_id)
	{
		return $this->db->query('select * from block_instances where id = ? limit 1',
			array($instance_id)
		)->first_row();
	}
}
?>